//
//  MTTagViewController.swift
//  MT
//
//  Created by M on 2020/1/4.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
/// 网络、通用
import MTCategory

import Moya
import Result
import RxSwift
import RxCocoa
/// 其它
import YPNavigationBarTransition

protocol MTTagViewControllerDelegate: NSObjectProtocol {
    /// 成功保存回调已选 tag
    func tagViewController(_ controller: MTTagViewController, successfullySavedWithTagType type: MTTagViewController.TagType, withSelectedModels models: [MTTagModel])
}

class MTTagViewController: BaseViewController {
    
    weak var delegate: MTTagViewControllerDelegate?

    var results: [MTTagModel]? {
        didSet {
            collectionView.models = results
        }
    }
    
    /// TagApi Provider
    private lazy var provider: MTProvider<TagApi> = {
        return MTProvider<TagApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    lazy var collectionView: MTTagCollectionView = {
        let cv = MTTagCollectionView(frame: view.bounds)
        cv.interactionDelegate = self
        cv.colorStyle = .background0x161616
        return cv
    }()
    
    @objc
    enum TagType: Int {
        case personality = 1
        case hobby = 2
        
        var controllerName: String {
            switch self {
            case .personality:
                return "我的标签"
            case .hobby:
                return "我的兴趣"
            }
        }
    }
    var tagType: TagType
    
    init(tagType: TagType) {
        self.tagType = tagType
        super.init(rounterParams: nil)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    required public init(rounterParams params: Dictionary<String, Any>?) {
        fatalError("init(rounterParams:) has not been implemented")
    }
    
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTTagViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
        initializeUI()
        requestTags()
    }
    
}


// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTTagViewController {
    
    private func setup() {
        let r_btn = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
        r_btn.setBackgroundImage(UIImage(color: UIColor(hex: 0x5d5d5d)), for: .disabled)
        r_btn.setBackgroundImage(UIImage(color: UIColor.theme.main), for: .normal)
        r_btn.setTitle("保存", for: .normal)
        r_btn.setTitleColor(.black, for: .normal)
        r_btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        r_btn.adjustsImageWhenHighlighted = false
        r_btn.layer.cornerRadius = 3
        r_btn.clipsToBounds = true
        r_btn.addTarget(self, action: #selector(tagViewController(didClickSaveButton:)), for: .touchUpInside)
        let rightButton = UIBarButtonItem(customView: r_btn)
        self.navigationItem.rightBarButtonItem = rightButton
        
        self.navigationItem.title = tagType.controllerName
    }
    
    private func initializeUI() {
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(view)
            make.bottom.equalTo(view).offset(0)
        }
    }
    
}

// MARK: ------------------------------------ 数据请求 ----------------------------------------
extension MTTagViewController {
    
    /// 请求 标签列表
    private func requestTags() {
        provider.rx.requestResult(.list(type: self.tagType.rawValue)).subscribe(onNext: { [weak self] (result: Result<MTTagResponseModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if let code = response.code, code == 200, var result = response.result {
                    if let otherTag = MTTagModel(JSON: ["name": "其它 +"]) {
                        result.append(otherTag)
                    }
                    weakself.results = result
                }
                break
                
            case .failure:
                break
            }
        }).disposed(by: disposeBag)
    }
    
    /// 保存标签或兴趣
    private func saveTags(withType type: Int, models: [MTTagModel], completion: @escaping (_ flag: Bool) -> Swift.Void) {
        let params = models.toJSON()
        var newparams = [[String:Any]]()
        for var param in params {
            param["tagType"] = type
            newparams.append(param)
        }
        
        
        provider.originRequest(.save(params: newparams, type: type), callbackQueue: nil, progress: nil) { (result, _) in
            switch result {
            case let .success(response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int, code == 200 {
                    completion(true)
                } else {
                    completion(false)
                }
                break
                
            case .failure:
                completion(false)
                break
            }
        }
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTTagViewController {
    
    private func tagViewController(didClickSaveButton sender: UIBarButtonItem) {
        saveTags(withType: self.tagType.rawValue, models: collectionView.selectedModels) { [weak self] (flag) in
            guard let weakself = self else { return }
            if flag {
                if let delegate = weakself.delegate {
                    delegate.tagViewController(weakself, successfullySavedWithTagType: weakself.tagType, withSelectedModels: weakself.collectionView.selectedModels)
                }
                AlertManager.presentAlertView(message: "保存成功", duration: 1, autoPresent: true) {
                    weakself.navigationController?.popViewController(animated: true)
                }
            } else {
                AlertManager.presentAlertView(message: "保存失败")
            }
        }
    }
    
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ MTTagCollectionViewDelegate ----------------------------------------
extension MTTagViewController: MTTagCollectionViewDelegate {
    
    func tagCollectionViewShouldPushToEditTagController(_ collectionView: MTTagCollectionView) {
        let c = MTEditTagViewController()
        c.tagType = self.tagType
        c.delegate = self
        self.navigationController?.pushViewController(c, animated: true)
    }
    
}

// MARK: ------------------------------------ MTEditTagViewControllerDelegate ----------------------------------------
extension MTTagViewController: MTEditTagViewControllerDelegate {

    func editTagViewController(_ controller: MTEditTagViewController, didEditTagWithName name: String) {
        guard let results = results else {
            return
        }
        
        /// 校验重名
        for result in results {
            if result.name == name {
                result.tagged = 1
                if !self.collectionView.selectedModels.contains(where: { (m) -> Bool in
                    return result.name == m.name
                }) {
                    self.collectionView.selectedModels.append(result)
                }
                self.collectionView.reloadData()
                return
            }
        }
        
        /// 没重名 创建
        if let model = MTTagModel(JSON: ["name": name]) {
            model.isSystem = 2
            model.tagged = 1
            self.collectionView.selectedModels.append(model)
            self.results?.insert(model, at: results.count - 1)
        }
    }
    
}
